//
//  CAISegmentedControl.m
//  Demo
//
//  Created by simon on 2017/9/5.
//  Copyright © 2017年 simon. All rights reserved.
//

#import "CAISegmentedControl.h"
#import "CAISegmentCell.h"

@interface CAISegmentedControl ()<UICollectionViewDelegateFlowLayout,UICollectionViewDataSource>

@property (nonatomic, strong) NSMutableArray *dataSources;

///选中指示条线
@property (nonatomic, strong) UIView *selectedIndicateView;

///整个视图的底部线条
@property (nonatomic, strong) UIView *bottomDivideLine;

///指示图标
@property (nonatomic, strong) UIImage *indicativeCircularImage;

@end

@implementation CAISegmentedControl

#pragma mark - 初始化

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self commonInit];
     }
    return self;
}


- (instancetype)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];
    if (self){
        [self commonInit];
    }
    return self;
}

+ (instancetype)segmentControlWithSectionTitles:(NSArray<NSString *> *)titles {
    CAISegmentedControl *segment = [[CAISegmentedControl alloc]init];
    [segment setSectionTitles:titles];
    return segment;
}



- (void)commonInit
{
    self.backgroundColor = [UIColor whiteColor];
    self.selectedColor = [UIColor redColor];
    self.normalColor = [UIColor blackColor];
    self.selectedIndex = NSNotFound;
    self.hideBottomDivideLine = NO;
    self.segmentEdgeInset = UIEdgeInsetsMake(0, 8, 0, 8);
    self.minimumItemSpacing = 10.f;
    self.selectionIndicatorColor = self.selectedColor;
    self.selectionIndicatorHeight = 3.f;
    self.widthStyle = CAISegmentedControlSegmentItemWidthStyleDynamic;
    self.selectionIndicatorMargin = UIEdgeInsetsMake(0, 0, 1, 0);
    [self addSubview:self.collectionView];
    //先添加collectionView，再添加selectedIndicateView
    [self.collectionView addSubview:self.selectedIndicateView];
    [self addSubview:self.bottomDivideLine];
}

//所有属性设置完后，一定要调用一下reloadData根据参数重新布局，不然属性设置无效果；
- (void)reloadData
{
    if (self.selectedIndex !=NSNotFound)
    {
        [self.dataSources enumerateObjectsUsingBlock:^(ZXSegmentModel*  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            
            obj.selected = self.selectedIndex==idx?YES:NO;
        }];
    }
    [self.collectionView reloadData];
    self.bottomDivideLine.hidden = self.hideBottomDivideLine;

}


- (void)setSelectedIndex:(NSInteger)selectedIndex animation:(BOOL)animation {
    if (selectedIndex>=self.dataSources.count){
        NSLog(@"越界了");
        return;
    }
    _selectedIndex = selectedIndex;
    [self.dataSources enumerateObjectsUsingBlock:^(ZXSegmentModel*  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (idx == selectedIndex) {
            obj.selected = YES;
        }
        else{
            obj.selected = NO;
        }
    }];
    [self.collectionView reloadData];
    // 滚动到哪里；
    NSIndexPath *selectIndexPath = [NSIndexPath indexPathForRow:selectedIndex inSection:0];
    [self.collectionView scrollToItemAtIndexPath:selectIndexPath atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:animation];
    [self moveLineToIndexPath:selectIndexPath animation:YES];
}




#pragma mark - UICollectionViewDataSource

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.dataSources.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    CAISegmentCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([CAISegmentCell class]) forIndexPath:indexPath];
//    cell.backgroundColor = [UIColor blueColor];
    cell.selectedColor = self.selectedColor;
    cell.normalColor = self.normalColor;
    cell.normalFont= self.font;
    cell.selectedFont = self.selectedFont;
    ZXSegmentModel *model = [self.dataSources objectAtIndex:indexPath.row];
    if (model.title)
    {
        cell.title = model.title;
    }
    else if (model.attributedTitle)
    {
        cell.attributedTitle = model.attributedTitle;
    }
    cell.isSelected = model.selected;
    return cell;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat height = CGRectGetHeight(self.frame)-self.segmentEdgeInset.top-self.segmentEdgeInset.bottom;
    height = MAX(height, 30);
    if (self.widthStyle == CAISegmentedControlSegmentItemWidthStyleFixed)
    {
        CGFloat width = (CGRectGetWidth(self.frame)-self.minimumItemSpacing*(self.dataSources.count-1)-self.segmentEdgeInset.left-self.segmentEdgeInset.right)/self.dataSources.count;
        return CGSizeMake(width, height);
    }
    //  cell是计算宽度,
    ZXSegmentModel *model = [self.dataSources objectAtIndex:indexPath.row];
    return CGSizeMake(model.width, height);
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return self.segmentEdgeInset;
}



- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    return self.minimumItemSpacing;
}

- (void)collectionView:(UICollectionView *)collectionView willDisplayCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath
{
    if ([self.delegate respondsToSelector:@selector(segmentControl:willDisplayCell:forItemAtIndexPath:)])
    {
        CAISegmentCell *cell1 = (CAISegmentCell *)cell;
        [self.delegate segmentControl:self willDisplayCell:cell1 forItemAtIndexPath:indexPath];
    }
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    [collectionView deselectItemAtIndexPath:indexPath animated:YES];
    
    [self setSelectedIndex:indexPath.row animation:YES];
    
    // 代理回调
    if (self.delegate && [self.delegate respondsToSelector:@selector(segmentControl:didSelectedIndex:)]) {
        
        [self.delegate segmentControl:self didSelectedIndex:indexPath.item];
    }
}

#pragma mark - UIScrollViewDelegate


- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    
//    NSIndexPath *path = [NSIndexPath indexPathForRow:_selectedIndex inSection:0];
//    [self moveLineToIndexPath:path animation:YES];
}

#pragma mark - 移动指示条（横线或图标）

- (void)moveLineToIndexPath:(NSIndexPath *)indexPath animation:(BOOL)animation
{
    UICollectionViewLayoutAttributes *layoutAttributes = [self.collectionView layoutAttributesForItemAtIndexPath:indexPath];
    ///宽度是动态的，需要重新赋值
    ZXSegmentModel *model = [self.dataSources objectAtIndex:indexPath.row];
    CGRect lineBounds = self.selectedIndicateView.bounds;
    if (self.selectionStyle == CAISegmentedControlSelectionStyleTextWidthStripe)
    {
        lineBounds.size.width = model.width;
    }
    else if (self.selectionStyle == CAISegmentedControlSelectionStyleExtendTextWidthStripe)
    {
        lineBounds.size.width = model.width + ZXSegmentedTitleExtendWidth;
    }
    else if (self.selectionStyle == CAISegmentedControlSelectionStyleFullWidthStripe)
    {
        lineBounds.size.width = layoutAttributes.size.width;
    }
    CGPoint lineCenter = self.selectedIndicateView.center;
    lineCenter.x = layoutAttributes.center.x;
    
    if (animation) {
        [UIView animateWithDuration:0.2 animations:^{
            self.selectedIndicateView.bounds = lineBounds;
            self.selectedIndicateView.center = lineCenter;
        }];
    }else{
        self.selectedIndicateView.bounds = lineBounds;
        self.selectedIndicateView.center = lineCenter;
    }
}

///1.父视图init初始化SegmentedControl，或添加SegmentedControl（addSubview），
///不会触发回调这个SegmentedControl的layoutSubviews方法；
///_segmentControl = [[CAISegmentedControl alloc]init] ;
///[self.view addSubview:_segmentControl];

///2.父视图控制器设置SegmentedControl的frame的时候，
///等走完父视图控制器的viewDidLayoutSubview会触发；


///初始化init及子视图添加；
///各种setter方法
///再走layoutSubviews；
#pragma mark - layoutSubviews
- (void)layoutSubviews {
    [super layoutSubviews];
    
    self.collectionView.frame = self.bounds;
    
    if (!self.hideBottomDivideLine) {
        [self bringSubviewToFront:self.bottomDivideLine];
        self.bottomDivideLine.frame = CGRectMake(0, CGRectGetHeight(self.frame) - 0.5, CGRectGetWidth(self.frame), 0.5);
    }else{
        self.bottomDivideLine.frame = CGRectMake(0, CGRectGetHeight(self.frame) - 0.5, CGRectGetWidth(self.frame), 0);
    }
    [self layoutselectedIndicateView];
}

- (void)layoutselectedIndicateView{
    
    NSInteger index = self.selectedIndex !=NSNotFound?self.selectedIndex:0;
    ZXSegmentModel *model = [self.dataSources objectAtIndex:index];
    NSIndexPath *indexPath = [NSIndexPath indexPathForItem:index inSection:0];
    //没有走代理方法的时候，是nil无cell;
    UICollectionViewLayoutAttributes *layoutAttributes = [self.collectionView layoutAttributesForItemAtIndexPath:indexPath];
    
    if (self.selectionStyle == CAISegmentedControlSelectionStyleCircular)
    {
        CGFloat selectedIndicateViewY = CGRectGetHeight(self.frame) - self.indicativeCircularImage.size.height-self.selectionIndicatorMargin.bottom-CGRectGetHeight(self.bottomDivideLine.frame);
        self.selectedIndicateView.frame = CGRectMake(0,selectedIndicateViewY, self.indicativeCircularImage.size.width, self.indicativeCircularImage.size.height);
    }else{
        CGFloat selectedIndicateViewY = CGRectGetHeight(self.frame) - self.selectionIndicatorHeight-self.selectionIndicatorMargin.bottom-CGRectGetHeight(self.bottomDivideLine.frame);
        if (self.selectionStyle == CAISegmentedControlSelectionStyleFullWidthStripe)
        {
            self.selectedIndicateView.frame = CGRectMake(0, selectedIndicateViewY, layoutAttributes.frame.size.width, self.selectionIndicatorHeight);
        }
        else if (self.selectionStyle == CAISegmentedControlSelectionStyleTextWidthStripe)
        {
            self.selectedIndicateView.frame = CGRectMake(0, selectedIndicateViewY, model.width, self.selectionIndicatorHeight);
        }
        else if (self.selectionStyle == CAISegmentedControlSelectionStyleExtendTextWidthStripe)
        {
            self.selectedIndicateView.frame = CGRectMake(0,selectedIndicateViewY, model.width+ZXSegmentedTitleExtendWidth, self.selectionIndicatorHeight);
        }
    }
    

    CGPoint lineCenter = self.selectedIndicateView.center;
    lineCenter.x = layoutAttributes.center.x;
    self.selectedIndicateView.center = lineCenter;
    NSLog(@"%@",NSStringFromCGPoint(lineCenter));
    

    if (self.selectionStyle != CAISegmentedControlSelectionStyleCircular) {
        self.selectedIndicateView.layer.masksToBounds = YES;
        self.selectedIndicateView.layer.cornerRadius = CGRectGetHeight(self.selectedIndicateView.frame)/2;
    }else{
        self.selectedIndicateView.layer.masksToBounds = NO;
    }
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

#pragma mark - Setter

- (void)setNormalColor:(UIColor *)normalColor
{
    _normalColor = normalColor;
}

- (void)setSelectedColor:(UIColor *)selectedColor
{
    _selectedColor = selectedColor;
}

- (void)setSectionTitles:(NSArray *)sectionTitles
{
    _sectionTitles = sectionTitles;
    NSMutableArray *tmpArr = [NSMutableArray arrayWithCapacity:sectionTitles.count];
    BOOL isDefault = YES;
    for (NSString *str in sectionTitles) {
        ZXSegmentModel *model = [[ZXSegmentModel alloc]init];
        model.title = str;
        model.font = self.font;
        if (isDefault) {
            model.selected = YES;
            isDefault = NO;
        }
        [tmpArr addObject:model];
    }
    self.dataSources = [NSMutableArray arrayWithArray:tmpArr];
}

- (void)setSelectedIndex:(NSInteger)selectedIndex
{
    if (selectedIndex ==NSNotFound)
    {
        return;
    }
    _selectedIndex = selectedIndex;
    if (selectedIndex<self.dataSources.count)
    {
        [self setSelectedIndex:selectedIndex animation:YES];
    }

}


- (void)setFont:(UIFont *)font{
    _font = font;
    if (self.dataSources.count > 0) {
        for (ZXSegmentModel *model in self.dataSources)
        {
            model.font = font;
        }
    }
}

/// 底下整个控件的分割线
- (void)setBottomDivideLineColor:(UIColor *)bottomDivideLineColor{
    _bottomDivideLineColor = bottomDivideLineColor;
    self.bottomDivideLine.backgroundColor = bottomDivideLineColor;
}

/// 选中指示条
- (void)setSelectionIndicatorColor:(UIColor *)selectionIndicatorColor{
    _selectionIndicatorColor = selectionIndicatorColor;
    self.selectedIndicateView.backgroundColor = selectionIndicatorColor;
}

- (void)setSelectionStyle:(CAISegmentedControlSelectionStyle)selectionStyle{
    _selectionStyle = selectionStyle;
    if (selectionStyle == CAISegmentedControlSelectionStyleCircular) {
        self.selectedIndicateView.backgroundColor = nil;
        self.selectedIndicateView.layer.contents =  (__bridge id _Nullable)self.indicativeCircularImage.CGImage;
        self.selectionIndicatorMargin = UIEdgeInsetsMake(0, 0, 4, 0);

    }else{
        self.selectedIndicateView.backgroundColor = self.selectionIndicatorColor;
        self.selectedIndicateView.layer.contents = nil;
        self.selectionIndicatorMargin = UIEdgeInsetsMake(0, 0, 1, 0);
    }
}

#pragma mark - Getter

- (UIView *)selectedIndicateView{
    if (_selectedIndicateView == nil) {
        UIView *view = [[UIView alloc]init];
        _selectedIndicateView = view;
    }
    return _selectedIndicateView;
}


- (UIView *)bottomDivideLine
{
    if (!_bottomDivideLine)
    {
        _bottomDivideLine = [[UIView alloc] init];
        _bottomDivideLine.backgroundColor = [UIColor colorWithRed:238.f/255.f green:238.f/255.f blue:238.f/255.f alpha:1];
    }
    return _bottomDivideLine;
}



- (UICollectionView *)collectionView {
    
    if (_collectionView == nil) {
        
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
        layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        UICollectionView *collection = [[UICollectionView alloc]initWithFrame:CGRectZero collectionViewLayout:layout];
        collection.delegate = self;
        collection.dataSource = self;
        collection.backgroundColor = self.backgroundColor;
        collection.showsVerticalScrollIndicator = NO;
        collection.showsHorizontalScrollIndicator = NO;
        [collection registerClass:[CAISegmentCell class] forCellWithReuseIdentifier:NSStringFromClass([CAISegmentCell class])];
        collection.backgroundColor = self.backgroundColor;
        _collectionView = collection;
    }
    return _collectionView;
}


- (UIImage *)indicativeCircularImage{
    if (!_indicativeCircularImage) {
        NSBundle *bundle1 = [NSBundle bundleForClass:[self class]];
        //.bundle
        NSString *path = [bundle1 pathForResource:@"CAISegmentedPageController" ofType:@"bundle"];
        NSBundle *bundle = [NSBundle bundleWithPath:path];
        UIImage *img = [UIImage imageNamed:@"indicator_icon" inBundle:bundle compatibleWithTraitCollection:nil];
        _indicativeCircularImage = img;
    }
    return _indicativeCircularImage;
}

@end



@implementation ZXSegmentModel

- (instancetype)init {
    self = [super init];
    if (self) {
        _selected = NO;
    }
    
    return self;
}
- (CGFloat)width
{
    if (_width <= 0)
    {
//        if (self.attributedTitle)
//        {
//            _width = self.attributedTitle.size.width+ZXSegmentedTitleExtendWidth;
//        }
//        else
//        {
//            NSString *string = self.title?self.title:self.attributedTitle.string;
//            CGFloat wid = [string boundingRectWithSize:CGSizeMake(0, 40) options:NSStringDrawingUsesFontLeading|NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:self.font} context:nil].size.width;
//
//            _width = wid + ZXSegmentedTitleExtendWidth;
//        }
        if (self.attributedTitle)
        {
            _width = self.attributedTitle.size.width;
        }
        else
        {
            NSString *string = self.title?self.title:self.attributedTitle.string;
            CGFloat wid = [string boundingRectWithSize:CGSizeMake(0, 40) options:NSStringDrawingUsesFontLeading|NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:self.font} context:nil].size.width;
            
            _width = wid;
        }
     }
    
    return _width;
}


@end
